package psi.vote.view.bean;

import model.Party;
import psi.vote.view.interfaces.IVoteSystem;
import psi.vote.view.service.VoteSystemRest;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created with IDEA.
 * Voter: Ѱ
 * Date: 12.10.14
 * Time: 12:31
 */
@ManagedBean
@SessionScoped
public class VoteBean implements Serializable {

    private IVoteSystem system = new VoteSystemRest();
    private int partyId;
    private List<Party> parties;
    private Map<String, Long> myRadioButtonList;
    private int page;
    private String userId = "vasya";

    public VoteBean() {
        parties = system.getAllParties(page);
        initRadio();

    }

    //Actions
    public String doVote() {
        ExternalContext externalContext =
                FacesContext.getCurrentInstance().getExternalContext();
        userId = externalContext.getRequestParameterMap().get("userId");

        boolean res = system.vote(userId, partyId);

        if(res)
        {
            return "/result.xhtml";
        }

        else {
            return "/vote.xhtml";
        }


    }
    public void initRadio() {
        myRadioButtonList = new HashMap<String, Long>();
        Iterator<Party> partyIterator = parties.iterator();
        while (partyIterator.hasNext()){
            Party tmp = partyIterator.next();
            myRadioButtonList.put(tmp.getName(), tmp.getId_party());
        }
    }

    public String nextPage() {

        if(!(parties.size() < 5))
        {
            page++;
        }
        parties = system.getAllParties(page);
        initRadio();
        return "/vote.xhtml";

    }

    public String prevPage() {
        if(page != 0)
        {
            page --;
        }
        parties = system.getAllParties(page);
        initRadio();
        return "/vote.xhtml";
    }



    public Map<String, Long> getMyRadioButtonList() {
        return myRadioButtonList;
    }

    public void setMyRadioButtonList(Map<String, Long> myRadioButtonList) {
        this.myRadioButtonList = myRadioButtonList;
    }

    public List<Party> getParties() {
        return parties;
    }

    public void setParties(List<Party> parties) {
        this.parties = parties;
    }

    public int getPartyId() {
        return partyId;
    }

    public void setPartyId(int partyId) {
        this.partyId = partyId;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }
}

